/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.service;

import com.alibaba.fastjson.JSON;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.storage.common.Constant;
import com.jeesite.modules.storage.common.MemberType;
import com.jeesite.modules.storage.dao.*;
import com.jeesite.modules.storage.entity.*;
import com.jeesite.modules.storage.util.AlipayUtil;
import com.jeesite.modules.storage.util.WeChatUtil;
import com.jeesite.modules.storage.util.WebUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

/**
 * 订单Service
 */
@Service
@Transactional(readOnly=true)
public class OrderService extends CrudService<OrderDao, Order> {

    @Autowired
    private OrderGoodsService orderGoodsService;

    @Autowired
    private OrderGoodsDao orderGoodsDao;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private CartDao cartDao;

    @Autowired
    private AddressService addressService;

    @Autowired
    private FreightTplService freightTplService;

    @Autowired
    private ActivityGoodsSpecDao activityGoodsSpecDao;

    @Autowired
    private ActivityGoodsService activityGoodsService;

    /**
     * 订单搜索
     * @param memberId 会员Id
     * @param keywords 关键字
     * @param size 每页数量
     * @param page 页码
     * @return 会员订单列表
     */
    public List<Map> getSearchList(String memberId, String keywords, Integer size, Integer page){
        List<Map> maps = dao.findSearchList(memberId,keywords,size * (page - 1),size);
        for (Map map : maps){
            map.put("orderGoodsList",orderGoodsDao.findListByOrderId(String.valueOf(map.get("orderId"))));
        }
        return maps;
    }

    /**
     * 获取会员订单列表【会员Id】
     * @param transMemberId 转发会员Id
     * @param memberId 会员Id
     * @param identity 标识【all全部 payment待付款 delivery待发货 recipient待收货 complete已完成】
     * @param size 每页数量
     * @param page 页码
     * @return 会员订单列表
     */
    public List<Map> getListByMemberId(String transMemberId,String memberId, String identity, Integer size, Integer page){
        List<Map> maps = dao.findListByMemberId(transMemberId,memberId,identity.equals("payment"),identity.equals("delivery"),identity.equals("recipient"),identity.equals("complete"),size * (page - 1),size);
        for (Map map : maps){
            map.put("orderGoodsList",orderGoodsDao.findListByOrderId(String.valueOf(map.get("orderId"))));
        }
        return maps;
    }

    /**
     * 获取订单详情【会员Id】
     * @param orderId 订单Id
     * @return 订单详情
     */
    public Map getContentById(String orderId){
        Map map = dao.findById(orderId);
        map.put("orderGoodsList",orderGoodsDao.findListByOrderId(String.valueOf(map.get("orderId"))));
        String receiveId = String.valueOf(map.get("receiveId"));
        if(StringUtils.isNotBlank(receiveId)){
            map.put("receive",addressService.getById(receiveId));
        }
        String sendId = String.valueOf(map.get("sendId"));
        if(StringUtils.isNotBlank(sendId)){
            map.put("send",addressService.getById(sendId));
        }
        return map;
    }

    /**
     * 获取价格信息
     * @param memberId 会员Id
     * @param transActivityId 转发Id
     * @param goodsSpecId  商品规格Id
     * @param num 数量
     * @param carts 购物车
     * @return
     */
    public Map getPrice(String memberId, String transActivityId, String goodsSpecId, Integer num, String carts,String addressId)
    {
        Map map = new HashMap();

        String type = memberDao.findTypeById(memberId);
        Double amount = 0d;
        Double freight = 0d;
        Map activityGoodsSpecMap = StringUtils.isNotBlank(goodsSpecId) ? activityGoodsSpecDao.findById(goodsSpecId) : new HashMap();
        Address address =StringUtils.isNotBlank(addressId) ?  addressService.get(addressId) : null;

        //直接购买
        if(StringUtils.isBlank(carts)){
            amount += WebUtil.getSalePrice(type,activityGoodsSpecMap) * num;
            freight += address == null ? 0 : (type.equals(MemberType.VIP_TYPE) && address.getIsDefault() ? 0 :freightTplService.getFreight(num,String.valueOf(activityGoodsSpecMap.get("brandId")),address.getProvince()));
        }
        //购物车
        else{
            ArrayList<String> array = JSON.parseObject(carts, ArrayList.class);
            num = array.size();
            for(String cartId : array) {
                Map cartMap = cartDao.findById(cartId);
                amount += WebUtil.getSalePrice(type,cartMap);
                freight += address == null ? 0 : (type.equals(MemberType.VIP_TYPE) && address.getIsDefault() ? 0 :freightTplService.getFreight(Integer.parseInt(String.valueOf(cartMap.get("num"))),String.valueOf(cartMap.get("brandId")),address.getProvince()));
            }
        }

        map.put("num",num);
        map.put("amount",amount);
        map.put("freight",freight);
        map.put("total",amount + freight);
        return map;
    }

    /**
     * 保存
     * @param platform 平台【APP或H5】
     * @param transMemberId 转发会员Id
     * @param memberId 会员Id
     * @param transActivityId 转发Id
     * @param parentId 父级Id
     * @param brandId 品牌Id
     * @param num 数量
     * @param amount 金额
     * @param receiveId 收件人Id【收货地址】
     * @param sendId 寄件人Id【收货地址】
     * @param payMethod 支付方式【Alipay或Wechat】
     * @param title 商品标题
     * @return
     */
    @Transactional(readOnly=false)
    public String save(String platform, String transMemberId,String memberId, String transActivityId, String parentId, String brandId, Integer num,Double amount, String receiveId, String sendId, String payMethod, Double freight, String title)
    {
        Order order = new Order();
        order.setPlatform(platform);
        order.setTransMemberId(transMemberId);
        order.setMemberId(memberId);
        order.setTransActivityId(transActivityId);
        order.setParentId(parentId);
        order.setBrandId(brandId);
        order.setNum(num);
        order.setAmount(amount);
        order.setTotal(amount + freight);
        order.setReceiveId(receiveId);
        order.setSendId(sendId);
        order.setPayMethod(payMethod);
        order.setFreight(freight);
        order.setStatus("待支付");
        order.setIsDeleted(false);
        order.setTitle(title);
        super.save(order);
        return order.getId();
    }

    /**
     * 直接购买
     * @param type 会员类型
     * @param platform 平台【APP或H5】
     * @param transMemberId 转发会员Id
     * @param memberId 会员Id
     * @param transActivityId 转发Id
     * @param goodsSpecId  商品规格Id
     * @param num 数量
     * @param remark 备注
     * @param receive 收件【收货地址】
     * @param sendId 寄件Id【收货地址】
     * @param payMethod 支付方式【Alipay或Wechat】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer buy(String type, String platform, String transMemberId,String memberId, String transActivityId, String goodsSpecId, Integer num,String remark, Address receive,String sendId,String payMethod)
    {
        Map map = activityGoodsSpecDao.findById(goodsSpecId);
        String brandId = String.valueOf(map.get("brandId"));
        Double salePrice = WebUtil.getSalePrice(type,map);
        Double agentPrice = WebUtil.getAgentPrice(map);
        Double freight = freightTplService.getFreight(num,brandId,receive.getProvince());
        Double amount = salePrice * num;
        String goodsName = String.valueOf(map.get("goodsName"));
        String orderId = save(platform, transMemberId, memberId,transActivityId, Constant.DEFAULT_ID,brandId,num,amount,receive.getId(),sendId,payMethod,freight,goodsName);
        orderGoodsService.save(transMemberId, memberId,transActivityId,orderId,null,goodsSpecId,salePrice,agentPrice, num,remark);
        return 200;
    }

    /**
     * 结算【购物车从】
     * @param type 会员类型
     * @param platform 平台【APP或H5】
     * @param transMemberId 转发会员Id
     * @param memberId 会员Id
     * @param carts 购物车
     * @param receive 收件【收货地址】
     * @param sendId 寄件Id【收货地址】
     * @param payMethod 支付方式【Alipay或Wechat】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer settlement(String type, String platform, String transMemberId,String memberId,String transActivityId, String carts,Address receive,String sendId,String payMethod)
    {
        ArrayList<String> array = JSON.parseObject(carts, ArrayList.class);
        List<OrderGoods> orderGoodsList = new ArrayList<>();
        List<String> brandIdList = new ArrayList<>();
        for(String cartId : array){
            OrderGoods orderGoods = new OrderGoods();

            Map cartMap = cartDao.findById(cartId);
            String goodsId = String.valueOf(cartMap.get("goodsId"));

            String brandId = goodsService.getBrandIdById(goodsId);
            if(!brandIdList.contains(brandId)){
                brandIdList.add(brandId);
            }

            orderGoods.setTransActivityId(String.valueOf(cartMap.get("transActivityId")));
            orderGoods.setActivityId(String.valueOf(cartMap.get("activityId")));
            orderGoods.setBrandId(brandId);
            orderGoods.setCartId(cartId);
            orderGoods.setGoodsId(goodsId);
            String goodsSpecId = String.valueOf(cartMap.get("goodsSpecId"));
            orderGoods.setGoodsSpecId(goodsSpecId);

            Map pricesMap = goodsService.getPrices(goodsSpecId);
            Double salePrice = WebUtil.getSalePrice(type,pricesMap);
            Double agentPrice = WebUtil.getAgentPrice(pricesMap);
            Integer num = Integer.parseInt(String.valueOf(cartMap.get("num")));
            orderGoods.setSalePrice(salePrice);
            orderGoods.setAgentPrice(agentPrice);
            orderGoods.setNum(num);
            orderGoods.setAmount(salePrice * num);
            orderGoods.setRemark(String.valueOf(cartMap.get("remark")));

            orderGoodsList.add(orderGoods);
        }

        String orderId = "";
        if(brandIdList.size() == 1){
            String title = "";
            Integer num = 0;
            Double amount = 0d;
            Double freight = 0d;

            for(OrderGoods orderGoods : orderGoodsList){
                ActivityGoods activityGoods = activityGoodsService.get(orderGoods.getGoodsId());
                title = activityGoods.getName();
                num += orderGoods.getNum();
                amount += orderGoods.getSalePrice()* orderGoods.getNum();
                freight += freightTplService.getFreight(orderGoods.getNum(),orderGoods.getBrandId(),receive.getProvince());
            }

            orderId = save(platform,transMemberId,memberId,transActivityId,Constant.DEFAULT_ID,brandIdList.get(0), num,amount,receive.getId(),sendId,payMethod,freight,title);
            for(OrderGoods orderGoods : orderGoodsList){
                orderGoodsService.save(transMemberId, memberId,transActivityId,orderId,orderGoods.getCartId(),orderGoods.getGoodsSpecId(),orderGoods.getSalePrice(),orderGoods.getAgentPrice(),orderGoods.getNum(),orderGoods.getRemark());
            }
        }

        if(brandIdList.size() > 1){
            String title = "";
            Integer num = 0;
            Double amount = 0d;
            Double freight = 0d;

            for(OrderGoods orderGoods : orderGoodsList){
                if(StringUtils.isBlank(title)){
                    ActivityGoods activityGoods = activityGoodsService.get(orderGoods.getGoodsId());
                    title = activityGoods.getName();
                }
                num += orderGoods.getNum();
                amount += orderGoods.getSalePrice()* orderGoods.getNum();
                freight += freightTplService.getFreight(orderGoods.getNum(),orderGoods.getBrandId(),receive.getProvince());
            }
            orderId = save(platform,transMemberId,memberId,transActivityId,null,null, num,amount,receive.getId(),sendId,payMethod,freight,title);

            for (String brandId : brandIdList){
                title = "";
                num = 0;
                amount = 0d;
                freight = 0d;

                for(OrderGoods orderGoods : orderGoodsList){
                    if(!orderGoods.getBrandId().equals(brandId)){
                        continue;
                    }
                    if(StringUtils.isBlank(title)){
                        ActivityGoods activityGoods = activityGoodsService.get(orderGoods.getGoodsId());
                        title = activityGoods.getName();
                    }
                    num += orderGoods.getNum();
                    amount += orderGoods.getSalePrice()* orderGoods.getNum();
                    freight += freightTplService.getFreight(orderGoods.getNum(),orderGoods.getBrandId(),receive.getProvince());
                }
                String brandOrderId = save(platform,transMemberId,memberId,transActivityId,orderId,brandId, num,amount,receive.getId(),sendId,payMethod,freight,title);
                for(OrderGoods orderGoods : orderGoodsList){
                    if(!orderGoods.getBrandId().equals(brandId)){
                        continue;
                    }
                    orderGoodsService.save(transMemberId, memberId,transActivityId,brandOrderId,orderGoods.getCartId(),orderGoods.getGoodsSpecId(),orderGoods.getSalePrice(),orderGoods.getAgentPrice(),orderGoods.getNum(),orderGoods.getRemark());
                }
            }
        }

        for(String cartId : array) {
            cartDao.phyDelete(new Cart(cartId));
        }

        return 200;
    }

    /**
     * 下单
     * @param platform 平台【APP或H5】
     * @param transMemberId 转发会员Id
     * @param memberId 会员Id
     * @param transActivityId 转发Id
     * @param goodsSpecId  商品规格Id
     * @param num 数量
     * @param remark 备注
     * @param carts 购物车
     * @param receiveId 收件Id【收货地址】
     * @param sendId 寄件Id【收货地址】
     * @param payMethod 支付方式【Alipay或Wechat】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer submit(String platform, String transMemberId,String memberId, String transActivityId, String goodsSpecId, Integer num, String remark,String carts,String receiveId,String sendId,String payMethod)
    {
        String type = memberDao.findTypeById(memberId);
        Address receiveAddress = addressService.setBak(receiveId);
        Address sendAddress = StringUtils.isBlank(sendId) ? null : addressService.setBak(sendId);
        return StringUtils.isNotBlank(carts) ? settlement(type, platform,transMemberId,memberId,transActivityId,carts,receiveAddress,sendAddress !=null ? sendAddress.getId() : null,payMethod) : buy(type, platform,transMemberId, memberId,transActivityId,goodsSpecId,num,remark,receiveAddress,sendAddress !=null ? sendAddress.getId() : null,payMethod);
    }

    /**
     * 获取订单Id【会员Id】
     * @param memberId 会员Id
     * @return 订单Id
     */
    public String getIdByMemberId(String transMemberId, String memberId){
        return dao.findIdByMemberId(transMemberId,memberId);
    }

    /**
     * 获取订单列表
     * @param orderId 订单Id
     * @return
     */
    public List<Order> getOrders(String orderId) {
        Order order = super.get(orderId);
        List<Order> orders = new ArrayList<>();
        if(order.getParentId().equals(Constant.DEFAULT_ID)){
            Order filterOrder = new Order();
            filterOrder.setParentId(orderId);
            List<Order> childOrders = super.findList(filterOrder);
            for (Order childOrder : childOrders){
                orders.add(childOrder);
            }
            orders.add(order);
        }else{
            orders.add(order);
        }
        return orders;
    }

    /**
     * 确认收货
     * @param orderId 订单Id【订单】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer recipient(String orderId)
    {
        Order order = new Order(orderId);
        order.setStatus("已完成");
        order.setRecipientDate(new Date());
        super.save(order);
        return 200;
    }

    /**
     * 删除
     * @param orderId 订单Id【订单】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer remove(String orderId)
    {
        Order order = new Order(orderId);
        order.setIsDeleted(true);
        order.setDeletedDate(new Date());
        super.save(order);
        return 200;
    }

    /**
     * 获取会员售后订单列表【会员Id】
     * @param transMemberId 转发会员Id
     * @param memberId 会员Id
     * @param identity 标识【all全部 waiting待处理 processing处理中 complete已完成 reject已驳回】
     * @param size 每页数量
     * @param page 页码
     * @return 会员售后订单列表
     */
    public List<Map> getServiceListByMemberId(String transMemberId, String memberId, String identity, Integer size, Integer page){
        List<Map> maps = dao.findServiceListByMemberId(transMemberId,memberId,identity.equals("waiting"),identity.equals("processing"),identity.equals("complete"),identity.equals("reject"),size * (page - 1),size);
        for (Map map : maps){
            map.put("orderGoodsList",orderGoodsDao.findServiceListByOrderId(String.valueOf(map.get("orderId"))));
        }
        return maps;
    }

    /**
     * 获取小B售后订单列表【会员Id】
     * @param memberId 会员Id
     * @param identity 标识【all全部 waiting待处理 processing处理中 complete已完成 reject已驳回】
     * @param size 每页数量
     * @param page 页码
     * @return 会员售后订单列表
     */
    public List<Map> getHandleListByMemberId(String memberId, String identity, Integer size, Integer page){
        List<Map> maps = dao.findHandleListByMemberId(memberId,identity.equals("waiting"),identity.equals("processing"),identity.equals("complete"),identity.equals("reject"),size * (page - 1),size);
        for (Map map : maps){
            map.put("orderGoodsList",orderGoodsDao.findServiceListByOrderId(String.valueOf(map.get("orderId"))));
        }
        return maps;
    }

    /**
     * 获取售后发起内容
     * @param memberId 会员Id【会员】
     * @param orderId 订单Id【订单】
     * @return 售后发起内容
     */
    public Map getServiceFormById(String memberId, String orderId){
        String type = memberDao.findTypeById(memberId);
        Map map = new HashMap();
        if(type.equals(MemberType.VIP_TYPE)){
            map.put("totalNum",10);
            map.put("residueNum",10);
        }
        List<Map> orderGoodsList = orderGoodsDao.findListByOrderId(orderId);
        for (Map orderGoods : orderGoodsList){
            orderGoods.put("serviceNum",orderGoods.get("num"));
        }
        map.put("orderGoodsList",orderGoodsList);
        return map;
    }

    /**
     * 售后提交
     * @param orderId 订单Id【订单】
     * @param type 类型
     * @param goods 商品
     * @param images 凭证
     * @param reason 原因
     * @return
     */
    @Transactional(readOnly=false)
    public Integer serviceSubmit(String orderId,String type,String goods,String images,String reason)
    {
        ArrayList<Map> maps = JSON.parseObject(goods, ArrayList.class);
        Integer serviceNum = 0;
        Double serviceAmount = 0d;
        for (Map map : maps){
            OrderGoods orderGoods = orderGoodsService.get(String.valueOf(map.get("orderGoodsId")));
            Integer num = Integer.parseInt(String.valueOf(map.get("serviceNum")));
            Double amount = orderGoods.getSalePrice() * num;
            orderGoods.setServiceNum(num);
            orderGoods.setServiceAmount(amount);
            serviceNum+= num;
            serviceAmount += amount;
            orderGoodsService.save(orderGoods);
        }
        Order order = new Order(orderId);
        order.setServiceType(type);
        order.setServiceImage(String.join("|", JSON.parseObject(images, ArrayList.class)));
        order.setServiceReason(reason);
        order.setServiceDate(new Date());
        order.setServiceNum(serviceNum);
        order.setServiceAmount(serviceAmount);

        order.setServiceStatus("退货申请中");
        if(StringUtils.isNotBlank(order.getTransActivityId()))
        {
            order.setAgentAuditStatus("待审核");
        }else{
            order.setSysAuditStatus("待审核");
        }

        super.save(order);
        return 200;
    }

    /**
     * 获取售后详情
     * @param orderId 订单Id【订单】
     * @return 售后详情
     */
    public Map getServiceContentById(String orderId){
        Map map = dao.findById(orderId);
        String serviceImage = String.valueOf(map.get("serviceImage"));
        map.put("images",StringUtils.isBlank(serviceImage) ? new ArrayList<String>() : serviceImage.split("\\|"));
        List<Map> orderGoodsList = orderGoodsDao.findListByOrderId(orderId);
        map.put("orderGoodsList",orderGoodsList);
        return map;
    }

    /**
     * 代理审核
     * @param orderId 订单Id【订单】
     * @param result 审核结果【同意、拒绝】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer agentAudit(String orderId,String result,String reason)
    {
        Order order = new Order(orderId);
        order.setAgentAuditResult(result);
        order.setAgentAuditReason(reason);
        order.setAgentAuditDate(new Date());
        if(result.equals("同意")){
            order.setSysAuditStatus("待审核");
        }else{
            order.setServiceStatus("退款拒绝");
        }
        order.setAgentAuditStatus("已审核");
        super.save(order);
        return 200;
    }

    /**
     * 系统审核
     * @param orderId 订单Id【订单】
     * @param result 审核结果【同意、拒绝】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer sysAudit(String orderId,String result,String reason) throws Exception {
        Order order = super.get(orderId);
        order.setAgentAuditStatus("已审核");
        order.setSysAuditResult(result);
        order.setSysAuditReason(reason);
        order.setSysAuditDate(new Date());
        if(result.equals("同意")){
            order.setServiceStatus("待退货入库");
        }else{
            order.setServiceStatus("退款拒绝");
        }
        super.save(order);
        return 200;
    }

    /**
     * 收到退货
     * @param orderId 订单Id【订单】
     * @return 收到退货
     */
    @Transactional(readOnly=false)
    public Integer signed(String orderId) throws Exception {
        Order order = new Order(orderId);
        order.setServiceStatus("收到退货");
        super.save(order);
        List<Map> maps = orderGoodsDao.findServiceListByOrderId(orderId);
        //退款金额
        Double amount = 0d;
        for (Map map : maps){
            amount += Double.parseDouble(String.valueOf(map.get("serviceAmount")));
        }
        refund(orderId,order.getPlatform(),order.getPayMethod(),order.getPayTradeNo(),order.getTransActivityId(),"售后服务",amount);

        return 200;
    }

    /**
     * 获取订单列表【管理端】
     * @param status 订单状态
     * @param size 每页数量
     * @param page 页码
     * @return 订单列表
     */
   public List<Map> getListForManage(String status,Integer size, Integer page){
        return dao.findListForManage( status,size * (page - 1),size);
   }

    /**
     * 获取订单列表【管理端】
     * @param status 订单状态
     * @param size 每页数量
     * @param page 页码
     * @return 订单列表
     */
    public Page<Map> getListPageForManage(String status,Integer size, Integer page){
        Page<Map> mapPage = new Page<>();
        mapPage.setCount(dao.findListCountForManage(status));
        mapPage.setPageSize(size);
        mapPage.setPageNo(page);
        List<Map> maps = getListForManage(status,size,page);
        for (Map map : maps){
            map.put("orderGoodsList",orderGoodsDao.findListByOrderId(String.valueOf(map.get("orderId"))));
        }
        mapPage.setList(maps);
        return mapPage;
    }

    /**
     * 获取售后订单列表【管理端】
     * @param serviceStatus 售后状态
     * @param size 每页数量
     * @param page 页码
     * @return 售后订单列表
     */
    public Page<Map> getServiceListForManage(String serviceStatus, Integer size, Integer page){
        Page<Map> mapPage = new Page<>();
        mapPage.setCount(dao.findServiceListCountForManage(serviceStatus));
        mapPage.setPageSize(size);
        mapPage.setPageNo(page);
        List<Map> maps = dao.findServiceListForManage(serviceStatus,size * (page - 1),size);
        for (Map map : maps){
            map.put("orderGoodsList",orderGoodsDao.findServiceListByOrderId(String.valueOf(map.get("orderId"))));
        }
        mapPage.setList(maps);
        return mapPage;
    }

    /**
     * 支付
     * @param orderId 订单Id【订单】
     * @param platform 平台【APP或H5】
     * @param payMethod 平台【Alipay或者Wechat】
     * @param openId 微信OpenId
     * @return
     */
    @Transactional(readOnly=false)
    public Object doPay(String orderId,String platform,String payMethod,String openId) throws Exception {
        Order order = super.get(orderId);
        String outTradeNo = WebUtil.getTradeNoByOrderId(orderId);
        if(StringUtils.isNotBlank(openId)){
            order.setOpenId(openId);
        }
        order.setPayTradeNo(outTradeNo);
        super.save(order);

        if(platform.equals("APP")&&payMethod.equals("Wechat")){
            return WeChatUtil.createAppPay(outTradeNo,order.getTitle(),order.getTotal());
        }
        if(platform.equals("H5")&&payMethod.equals("Wechat")){
            return WeChatUtil.createJSAPIPay(outTradeNo,openId,order.getTitle(),order.getTotal());
        }
        if(platform.equals("APP")&&payMethod.equals("Alipay")){
            return AlipayUtil.createAppPay(outTradeNo,order.getTitle(),order.getTotal());
        }
        return true;
    }

    /**
     * 支付【回调】
     * @param orderId 订单Id【订单】
     * @param payTransactionId 微信交易号
     * @return
     */
    @Transactional(readOnly=false)
    public Integer payHandle(String orderId,String payTransactionId)
    {
        List<Order> orders = getOrders(orderId);
        for (Order order : orders){
            if(!order.getStatus().equals("待支付")){
                continue;
            }
            order.setPayDate(new Date());
            order.setStatus("待发货");
            order.setPayTransactionId(payTransactionId);
            super.save(order);
        }
        return 200;
    }

    /**
     * 取消订单
     * @param orderId 订单Id【订单】
     * @return
     * 200 成功
     * 201 退款失败
     */
    @Transactional(readOnly=false)
    public Integer cancel(String orderId) throws Exception {
        Order order = super.get(orderId);
        //已支付需退款
        if(order.getStatus().equals("待发货")){
            refund(orderId, order.getPlatform(),order.getPayMethod(),order.getPayTradeNo(),order.getTransActivityId(), "取消订单",order.getTotal());
            order.setStatus("退款中");
        }else{
            order.setStatus("已取消");
            order.setCancelDate(new Date());
        }
        super.save(order);
        return 200;
    }

    /**
     * 退款
     * @param outTradeNo 交易号
     * @return
     */
    public boolean refund(String orderId, String platform,String payMethod,String outTradeNo, String transactionId, String reason,Double amount) throws Exception {
        if(platform.equals("APP")&&payMethod.equals("Wechat")){
            return WeChatUtil.appRefund(orderId,transactionId,amount);
        }
        if(platform.equals("H5")&&payMethod.equals("Wechat")){
            return WeChatUtil.h5Refund(orderId,transactionId,amount);
        }
        if(platform.equals("APP")&&payMethod.equals("Alipay")){
            return AlipayUtil.refund(outTradeNo,reason,amount);
        }
        return true;
    }

    /**
     * 退款【回调】
     * @param orderId 订单Id【订单】
     * @return
     */
    @Transactional(readOnly=false)
    public Integer refundHandle(String orderId)
    {
        Order order = super.get(orderId);
        //取消订单
        if(StringUtils.isBlank(order.getServiceStatus()) && order.getStatus().equals("退款中")){
            order.setCancelDate(new Date());
            order.setStatus("已取消");
        }
        if(StringUtils.isNotBlank(order.getServiceStatus()) && order.getServiceStatus().equals("收到退货")){
            order.setRefundDate(new Date());
            order.setServiceStatus("已退款");
        }
        super.save(order);
        return 200;
    }

    /**
     * 统计汇总
     * @return 统计汇总
     */
    public Map getSaleStatistics(){
        Map map = new HashMap();
        map.put("profitAmount",0d);
        map.put("visitNum",0);
        map.put("orderNum",0);
        map.put("saleAmount",0d);
        return map;
    }

    /**
     * 统计汇总【日】
     * @param memberId 会员Id
     * @param dayDate 日期
     * @return 统计汇总
     */
    public Map getDaySaleStatistics(String memberId,String dayDate){
        return getSaleStatistics();
    }

    /**
     * 统计汇总【月】
     * @param memberId 会员Id
     * @param monthDate 日期
     * @return 统计汇总
     */
    public Map getMonthSaleStatistics(String memberId,String monthDate){
        return getSaleStatistics();
    }

    /**
     * 统计汇总【年】
     * @param memberId 会员Id
     * @param yearDate 日期
     * @return 统计汇总
     */
    public Map getYearSaleStatistics(String memberId,String yearDate){
        return getSaleStatistics();
    }

    /**
     * 获取销售列表【日】
     * @param memberId 会员Id
     * @param dayDate 日期
     * @param size 每页数量
     * @param page 页码
     * @return 销售列表
     */
    public List<Map> getDaySaleList(String memberId, String dayDate, Integer size, Integer page){
       return new ArrayList<>();
    }

    /**
     * 获取销售列表【月】
     * @param memberId 会员Id
     * @param monthDate 日期
     * @param size 每页数量
     * @param page 页码
     * @return 销售列表
     */
    public List<Map> getMonthSaleList(String memberId,String monthDate, Integer size, Integer page){
        return new ArrayList<>();
    }

    /**
     * 获取销售列表【年】
     * @param memberId 会员Id
     * @param yearDate 日期
     * @param size 每页数量
     * @param page 页码
     * @return 销售列表
     */
    public List<Map> getYearSaleList(String memberId,String yearDate, Integer size, Integer page){
        return new ArrayList<>();
    }
}